package com.utcook.host.fragmentdialog

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.Observable
import androidx.fragment.app.Fragment
import com.utcook.host.fragmentdialog.databinding.FragmentRecipeOperationBinding

class RecipeOperationFragment : Fragment() {

    private var _binding: FragmentRecipeOperationBinding? = null
    private val binding get() = _binding!!
    private var burnerViewModel: BurnerViewModel? = null

    private var recipeListFragment: RecipeListFragment? = null
    private val manualCookingFragments = mutableListOf<ManualCookingFragment>()
    private var currentContentFragment: Fragment? = null

    companion object {
        fun newInstance(viewModel: BurnerViewModel): RecipeOperationFragment {
            val fragment = RecipeOperationFragment()
            fragment.burnerViewModel = viewModel
            return fragment
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = FragmentRecipeOperationBinding.inflate(inflater, container, false)
        binding.fragment = this
        binding.viewModel = burnerViewModel
        
        setupViewModelListener()
        setupRecipeListFragment()
        setupManualCookingFragments()
        setupRecipeSelectionListener()
        
        return binding.root
    }

    private fun setupViewModelListener() {
        burnerViewModel?.let { viewModel ->
            viewModel.selectedBurnerIndex.addOnPropertyChangedCallback(
                object : Observable.OnPropertyChangedCallback() {
                    override fun onPropertyChanged(sender: Observable?, propertyId: Int) {
                        // 当选中炉头变化时，切换到对应的手动烹饪Fragment
                        if (!viewModel.isRecipeMode.get()) {
                            showManualCookingFragment(viewModel.selectedBurnerIndex.get())
                        }
                    }
                }
            )
            
            viewModel.isRecipeMode.addOnPropertyChangedCallback(
                object : Observable.OnPropertyChangedCallback() {
                    override fun onPropertyChanged(sender: Observable?, propertyId: Int) {
                        updateRecipeListVisibility()
                        // 当切换到手动烹饪模式时，显示当前选中炉头的手动烹饪Fragment
                        if (!viewModel.isRecipeMode.get()) {
                            showManualCookingFragment(viewModel.selectedBurnerIndex.get())
                        }
                    }
                }
            )
        }
    }

    private fun setupRecipeListFragment() {
        burnerViewModel?.let { viewModel ->
            recipeListFragment = RecipeListFragment.newInstance(viewModel)
            childFragmentManager.beginTransaction()
                .add(R.id.recipe_list_container, recipeListFragment!!, "recipe_list")
                .commit()
            currentContentFragment = recipeListFragment
        }
    }

    private fun setupManualCookingFragments() {
        burnerViewModel?.let { viewModel ->
            // 检查是否已经添加过Fragment
            val existingFragment = childFragmentManager.findFragmentByTag("manual_cooking_0")
            if (existingFragment != null) {
                // 如果已经存在，直接使用现有的Fragment
                manualCookingFragments.clear()
                for (i in 0..3) {
                    val fragment = childFragmentManager.findFragmentByTag("manual_cooking_$i") as? ManualCookingFragment
                    fragment?.let { manualCookingFragments.add(it) }
                }
                currentContentFragment = manualCookingFragments.getOrNull(0)
                return
            }
            
            // 创建4个手动烹饪Fragment，每个对应一个炉头
            for (i in 0..3) {
                val manualCookingFragment = ManualCookingFragment.newInstance(i, viewModel)
                manualCookingFragments.add(manualCookingFragment)
            }
            
            // 将所有手动烹饪Fragment添加到容器，但只显示第一个
            val transaction = childFragmentManager.beginTransaction()
            for (i in 0..3) {
                val fragment = manualCookingFragments[i]
                transaction.add(R.id.manual_cooking_container, fragment, "manual_cooking_$i")
                if (i != 0) {
                    transaction.hide(fragment)
                }
            }
            transaction.commit()
            currentContentFragment = manualCookingFragments[0]
        }
    }

    private fun updateRecipeListVisibility() {
        recipeListFragment?.let { fragment ->
            burnerViewModel?.let { viewModel ->
                if (viewModel.isRecipeMode.get()) {
                    showContentFragment(fragment)
                } else {
                    // 当切换到手动烹饪模式时，显示当前选中炉头的手动烹饪Fragment
                    showManualCookingFragment(viewModel.selectedBurnerIndex.get())
                }
            }
        }
    }

    private fun showContentFragment(fragment: Fragment) {
        if (currentContentFragment == fragment) return
        
        val transaction = childFragmentManager.beginTransaction()
        
        // 隐藏当前Fragment
        currentContentFragment?.let { transaction.hide(it) }
        
        // 显示目标Fragment
        transaction.show(fragment)
        
        transaction.commit()
        currentContentFragment = fragment
    }
    
    private fun showManualCookingFragment(burnerIndex: Int) {
        if (burnerIndex in 0..3) {
            val fragment = manualCookingFragments[burnerIndex]
            showContentFragment(fragment)
        }
    }

    private fun setupRecipeSelectionListener() {
        burnerViewModel?.let { viewModel ->
            viewModel.selectedRecipe.addOnPropertyChangedCallback(
                object : androidx.databinding.Observable.OnPropertyChangedCallback() {
                    override fun onPropertyChanged(sender: androidx.databinding.Observable?, propertyId: Int) {
                        viewModel.selectedRecipe.get()?.let { recipe ->
                            // 获取当前选中的炉头
                            val selectedBurnerIndex = viewModel.selectedBurnerIndex.get()
                            // 开始烹饪
                            viewModel.startCookingOnBurner(selectedBurnerIndex, recipe)
                        }
                    }
                }
            )
        }
    }

    fun onCookingModeChanged() {
        val recipeCookingChecked = binding.rbRecipeCooking.isChecked
        burnerViewModel?.setRecipeMode(recipeCookingChecked)
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
} 